<template>
  <div class="main-box mid-box">
    <div class="form-header">
      <i class="title-font">{{ userId ? '修改用户' : '添加用户' }}</i>
    </div>
    <div class="form-body">
      <el-form
        class="troila-form"
        :label-width="formLabelWidth"
        :model="form"
        :rules="rules"
        ref="form"
      >
        <div class="form-box">
          <el-form-item label="用户名" prop="loginName">
            <el-input
              v-model="form.loginName"
              auto-complete="off"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="userName">
            <el-input
              v-model="form.userName"
              auto-complete="off"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="form.sex">
              <el-radio
                :label="item.dictCode"
                v-for="item in sexList"
                :key="item.dictCode"
                >{{ item.dictName }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="邮箱账号" prop="email">
            <el-input
              v-model="form.email"
              auto-complete="off"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input
              v-model="form.phone"
              auto-complete="off"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item label="选择角色" prop="roleId">
            <el-select
              v-model="form.roleId"
              multiple
              filterable
              placeholder="请选择角色"
              popper-class="troila-popper"
            >
              <el-option
                :label="item.roleName"
                :value="item.id"
                v-for="(item, i) in dictionary.roleList"
                :key="i"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="btn-box">
            <el-button type="primary" :loading="ajaxIng" @click="submitForm"
              >确 定</el-button
            >
            <el-button @click="cancel">{{
              ajaxIng ? '返 回' : '取 消'
            }}</el-button>
          </el-form-item>
        </div>
        <div class="form-box">
          <el-form-item label="所属机构" prop="organizationId">
            <div class="el-input__inner userTree" v-loading="loading">
              <el-scrollbar
                v-if="dictionary.orgList && dictionary.orgList.length > 0"
              >
                <el-tree
                  :default-checked-keys="[form.organizationId]"
                  :data="dictionary.orgList"
                  show-checkbox
                  node-key="id"
                  check-strictly
                  default-expand-all
                  ref="tree"
                  :props="{
                    label: 'organizationName',
                  }"
                  @check="chooseOrg"
                ></el-tree>
                <!-- expand-on-click-node 是否在点击节点的时候展开或者收缩节点 -->
                <!-- check-on-click-node 是否在点击节点的时候选中节点 -->
              </el-scrollbar>
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
</template>
<script>
import { checkPhone, validEmail } from '../../../../../assets/js/validate'
export default {
  name: 'userForm',
  data() {
    const validateMobile = (rule, value, callback) => {
      if (value && !checkPhone(value)) {
        callback(new Error('手机号格式不正确'))
      } else {
        callback()
      }
    }
    const validateEmail = (rule, value, callback) => {
      if (value && !validEmail(value)) {
        callback(new Error('邮箱格式不正确'))
      } else {
        callback()
      }
    }
    return {
      ajaxIng: false,
      form: {
        loginName: '',
        userName: '',
        sex: '',
        email: '',
        phone: '',
        roleId: [],
        organizationId: '',
      },
      formLabelWidth: '120px', //标题文字宽度
      rules: {
        // 规则
        loginName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        userName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        roleId: [{ required: true, message: '请选择角色', trigger: 'change' }],
        organizationId: [
          { required: true, message: '请选择所属机构', trigger: 'change' },
        ],
        email: [{ validator: validateEmail, trigger: 'blur' }],
        phone: [{ validator: validateMobile, trigger: 'blur' }],
      },
      dictionary: {
        // 字典信息
        // sex: [
        //   { dictName: '男', dictCode: '1' },
        //   { dictName: '女', dictCode: '0' },
        // ],
        // status: [
        //   { dictName: '启用', dictCode: '1' },
        //   { dictName: '禁用', dictCode: '0' },
        // ],
        roleList: '',
        orgList: '',
      },
      userId: null,
      loading: false,
    }
  },
  computed: {
    sexList() {
      let list = this.$store.state.dictionary.user_sex
      if (!list) {
        this.$store.dispatch('dictionary/getDict', 'user_sex')
      }
      this.dictionary.sex = list
      return list ? list : []
    },
  },
  watch: {},
  methods: {
    filteIds() {
      if (this.dictionary.roleList && this.dictionary.roleList.length > 0) {
        let list = this.dictionary.roleList.map((v) => v.id)
        // console.log(
        //   list,
        //   this.form.roleId,
        //   this.form.roleId.filter((v) => list.indexOf(v) > -1)
        // )
        this.form.roleId = this.form.roleId
          ? this.form.roleId.filter((v) => list.indexOf(v) > -1)
          : null
      }
      this.$nextTick(() => {
        this.$refs.form ? this.$refs.form.clearValidate() : null
      })
    },
    getDropList() {
      this.API.roleManage.findList().then((res) => {
        if (res.code == '1') {
          this.dictionary.roleList = res.data
          this.filteIds()
          this.$nextTick(() => {
            this.$refs.form ? this.$refs.form.clearValidate() : null
          })
        }
      })
    },
    getOrgList() {
      this.loading = true
      this.API.organization
        .totalList()
        .then((res) => {
          if (res.code == '1') {
            this.dictionary.orgList = res.data
          }
          this.loading = false
        })
        .catch((err) => {
          this.loading = false
        })
    },
    chooseOrg(data) {
      this.form.organizationId = data.id
      this.$refs.tree.setCheckedKeys([this.form.organizationId])
      this.$nextTick((v) => {
        this.$refs.form.validateField('organizationId')
      })
    },
    cancel() {
      this.$router.back(-1)
    },
    submitForm(form) {
      if (this.ajaxIng) {
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.ajaxIng = true
          let params = {
            ...this.form,
          }
          if (this.userId) {
            params.id = this.userId
          }
          this.API.userManage[this.userId ? 'updateUser' : 'addUser'](params)
            .then((res) => {
              if (res.code == '1') {
                // this.showForm = false
                this.ajaxIng = false
                this.$alertFn.success(`${this.userId ? '修改' : '添加'}成功 ！`)
                this.cancel()
              } else {
                this.ajaxIng = false
              }
            })
            .catch((error) => {
              // this.$alertFn.error(
              //   `${this.userId ? '修改' : '添加'}失败 ！`
              // )
              this.ajaxIng = false
            })
        } else {
          // console.log('error submit!!')
          return false
        }
      })
    },
  },
  created() {
    // console.log(this.value)
    this.getDropList()
    this.getOrgList()
    if (this.$route.name == 'editUser') {
      this.userId = this.decode(this.$route.params.userId)
      let row = this.$route.params.row
      if (!this.userId || !row) {
        this.cancel()
        return
      }
      try {
        for (let k in row) {
          this.form[k] = row[k]
        }
        this.form.roleId = row.roles ? row.roles.map((v) => v.id) : null
        this.form.sex =
          this.form.sex || this.form.sex === 0 ? this.form.sex.toString() : null
      } catch (error) {
        this.cancel()
      }
    }
  },
}
</script>
<style  scoped>
.main-box {
  padding: 21px 22px 0 20px;
}
.form-box {
  width: 50%;
  display: inline-block;
  vertical-align: top;
  box-sizing: border-box;
}
.userTree {
  height: 300px !important;
  width: 300px;
  padding: 5px 0;
}
.userTree > div {
  height: 100%;
}
</style>